package com.xgc.book.bookserver.util.shiro;

import com.alibaba.fastjson.JSON;
import com.xgc.book.bookserver.bean.TokenBean;
import com.xgc.book.bookserver.bean.VipTokenBean;
import com.xgc.book.bookserver.service.TokenService;
import com.xgc.book.bookserver.service.VipTokenService;
import com.xgc.book.bookserver.util.ResultJson;
import com.xgc.book.bookserver.util.SpringContext;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author PangJunjie
 * @Date 2023/11/21/021
 */
public class Shiro2Filter extends AuthenticatingFilter {

    private String type = "admin";

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = getToken(request);
        if (token == null) return null;
        return new Shiro2Token(token);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = getToken(request);

        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

        if (StringUtils.isEmpty(token)) {
            response.getWriter().println(JSON.toJSON(ResultJson.error(401, "未携带token")));
            return false;
        } else {
            if ("admin".equals(type)) {
                TokenService tokenService = SpringContext.getBean(TokenService.class);
                TokenBean tokenBean = tokenService.getByToken(token);
                if (tokenBean == null || tokenBean.getExpires().getTime() < System.currentTimeMillis()) {
                    response.getWriter().println(JSON.toJSON(ResultJson.error(401, "token失效！")));
                    return false;
                } else {
                    return executeLogin(servletRequest, servletResponse);
                }
            } else {
                VipTokenService vipTokenService = SpringContext.getBean(VipTokenService.class);
                VipTokenBean vipTokenBean = vipTokenService.getByToken(token);
                if (vipTokenBean == null || vipTokenBean.getExpires().getTime() < System.currentTimeMillis()) {
                    response.getWriter().println(JSON.toJSON(ResultJson.error(401, "token失效！")));
                    return false;
                } else {
                    return executeLogin(servletRequest, servletResponse);
                }
            }

        }
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        return req.getMethod().equals(RequestMethod.OPTIONS.name());
    }

    private String getToken(HttpServletRequest request) {
        String token = null;
        String uri = request.getRequestURI();
        if (uri.contains("api")) {
            token = request.getHeader("apiToken");
            type = "api";
        } else if (uri.contains("wx")) {
            token = request.getHeader("wxToken");
            type = "wx";
        } else {
            token = request.getHeader("token");
            type = "admin";
        }
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return token;
    }
}
